from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from tools.models.models import Product2
import json


# 产品列表页面
def product_list(request):
    return render(request, '../templates/testing/product_list.html')


# 搜索产品
def search_products(request):
    query = request.GET.get('query', '')
    category = request.GET.get('category', '')

    print('query', query)
    print('category', category)

    products = Product2.objects.all()

    if query:
        products = products.filter(name__icontains=query)
    if category:
        products = products.filter(category__icontains=category)

    # 构建返回数据
    product_list = []
    for product in products:
        product_list.append({
            'id': product.id,
            'name': product.name,
            'category': product.category,
            'price': str(product.price),
            'description': product.description
        })
    print('product_list', product_list)

    return JsonResponse({'products': product_list})

# 添加产品
@csrf_exempt
def add_product(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 验证数据
            if not all(k in data for k in ('name', 'category', 'price', 'description')):
                return JsonResponse({'success': False, 'message': '缺少必要字段'})

            # 创建产品
            product = Product2(
                name=data['name'],
                category=data['category'],
                price=data['price'],
                description=data['description']
            )
            product.save()

            return JsonResponse({
                'success': True,
                'message': '产品添加成功',
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'category': product.category,
                    'price': str(product.price),
                    'description': product.description
                }
            })

        except Exception as e:
            return JsonResponse({'success': False, 'message': str(e)})

    return JsonResponse({'success': False, 'message': '请求方法错误'})

# 编辑产品
@csrf_exempt
def edit_product(request, product_id):
    try:
        product = Product2.objects.get(id=product_id)

        if request.method == 'GET':
            # 获取产品信息
            return JsonResponse({
                'success': True,
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'category': product.category,
                    'price': str(product.price),
                    'description': product.description
                }
            })

        elif request.method == 'POST':
            # 更新产品信息
            data = json.loads(request.body)

            # 验证数据
            if not all(k in data for k in ('name', 'category', 'price', 'description')):
                return JsonResponse({'success': False, 'message': '缺少必要字段'})

            product.name = data['name']
            product.category = data['category']
            product.price = data['price']
            product.description = data['description']
            product.save()

            return JsonResponse({
                'success': True,
                'message': '产品更新成功'
            })

    except ObjectDoesNotExist:
        return JsonResponse({'success': False, 'message': '产品不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})

    return JsonResponse({'success': False, 'message': '请求方法错误'})

# 删除产品
@csrf_exempt
def delete_product(request, product_id):
    try:
        product = Product2.objects.get(id=product_id)
        product.delete()
        return JsonResponse({'success': True, 'message': '产品删除成功'})
    except ObjectDoesNotExist:
        return JsonResponse({'success': False, 'message': '产品不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})
